﻿using System;
using System.Collections.Generic;
using CosyTrade.UI;
using DevExpress.XtraTreeList.Nodes;
using NHibernate.Expression;
using System.Reflection;

namespace CosyTrade.StoreManagement.UI
{
    public partial class ProductCategoryForm : AddinFormBase
    {
        private IProductManager productMgr;
        private ProductCategoryBase currentObject;

        public ProductCategoryForm()
        {
            InitializeComponent();
        }

        private void ProductCategoryForm_Load(object sender, EventArgs e)
        {
            productMgr = CurrentPortalFactory.RegisterProxy<IProductManager>("ProductManager");
            
            LoadCategoryTree();
        }

        private void LoadCategoryTree()
        {
            productCategoryTree.ClearNodes();

            IList<ProductCategoryBase> productCategories = productMgr.GetProductCategoryRootlist();

            if (productCategories == null) return;
            foreach (ProductCategoryBase category in productCategories)
            {
                TreeListNode treeListNode = productCategoryTree.AppendNode(new object[] {category.CategoryChinese,category.CategorySpanish,category},null);
                treeListNode.HasChildren = true;
                treeListNode.Tag = false;
            }
        }

        #region 方法

        private void AddNewProductCategory()
        {
            if (productMgr != null)
            {
                FrmProperty frmProperty = new FrmProperty(productMgr);
                frmProperty.IsNew = true;
                frmProperty.ProductCategorys = new ProductCategoryBase();
                if(frmProperty.ShowDialog()!=System.Windows.Forms.DialogResult.OK) return;

                ProductCategoryBase productCategory = frmProperty.ProductCategorys.GetChanges() as ProductCategoryBase;
                
                if (productCategory == null) return;
                ProductCategory newProduct = new ProductCategory();
                newProduct.CategoryChinese = productCategory.CategoryChinese;
                newProduct.CategorySpanish = productCategory.CategorySpanish;
                newProduct.Parent = productCategory.Parent;
                newProduct.GetType().BaseType.GetField("primaryKey", BindingFlags.Instance | BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.DeclaredOnly).SetValue(newProduct, productCategory.PrimaryKey); 

                productMgr.CreateProductCategory(newProduct, newProduct.Parent);
            }
            LoadCategoryTree();
        }

        private void UpdateProductCategory()
        {
            if (currentObject == null) return;
            Guid oldkey = currentObject.Parent;
            FrmProperty frmProperty = new FrmProperty(productMgr);
            frmProperty.ProductCategorys = currentObject;
            frmProperty.IsNew = false ;
            if (frmProperty.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;

            ProductCategoryBase productCategory = frmProperty.ProductCategorys.GetChanges() as ProductCategoryBase;
            if (productCategory == null) return;
            productMgr.UpdateProductCategory(productCategory, oldkey );
            LoadCategoryTree();
        }

        private void DeleteProductCategory()
        {
            if (currentObject == null) return;
            IList<Product> products = productMgr.GetProductList(Expression.Eq("Category", currentObject),1, 1);
            ProductCategory productCategory = productMgr.GetProductCategoryDetail(currentObject.PrimaryKey);
            if ((products!=null && products.Count>0) || productCategory != null && productCategory.Childs != null && productCategory.Childs.Count>0)
            {
                Functions.ShowMessageBox("无法执行删除操作！'" + currentObject.CategoryChinese + "(" + currentObject.CategorySpanish + ")'分类正在被使用。");
                return;
            }
            if (Functions.ShowConfigBox("确定要删除'" + currentObject.CategoryChinese + "(" + currentObject.CategorySpanish + "') 分类吗?") != System.Windows.Forms.DialogResult.Yes)
                return;
            productMgr.DeleteProductCategory(currentObject.PrimaryKey);
            LoadCategoryTree();
        }

        private ICriterion GetCriterion()
        {
            ICriterion criterion = null;
            if (!string.IsNullOrEmpty(CategoryNameCN.Text))
                criterion = Expression.Or(Expression.Eq("CategoryChinese", CategoryNameCN.Text), Expression.Like("CategoryChinese",CategoryNameCN.Text+"%"));
            if (!string.IsNullOrEmpty(CategoryNameSN.Text))
                criterion = criterion != null ? Expression.Or(Expression.Or(Expression.Eq("CategorySpanish", CategoryNameSN.Text), Expression.Like("CategorySpanish", CategoryNameSN.Text + "%")), criterion) 
                    : Expression.Or(Expression.Eq("CategorySpanish", CategoryNameSN.Text),Expression.Like("CategorySpanish", CategoryNameSN.Text + "%"));
            return criterion;
        }

        #endregion

        #region 事件

        private void productCategoryTree_BeforeExpand(object sender, DevExpress.XtraTreeList.BeforeExpandEventArgs e)
        {
            if (e.Node.Tag == null) return;
            if ((bool)e.Node.Tag) return;
            e.Node.Tag = true;

            ProductCategoryBase currentCategory = (ProductCategoryBase)e.Node.GetValue("pME");
            if (currentCategory != null)
            {
                ProductCategory productCategory = productMgr.GetProductCategoryDetail(currentCategory.PrimaryKey);
                if (productCategory == null) return;
                IList<ProductCategoryBase> list = productCategory.Childs;

                if (list == null) return;
                foreach (ProductCategoryBase categoryBase in list)
                {
                    TreeListNode listNode =
                        productCategoryTree.AppendNode(
                            new object[] {categoryBase.CategoryChinese, categoryBase.CategorySpanish, categoryBase},
                            e.Node);
                    listNode.HasChildren = true;
                    listNode.Tag = false;
                }
            }
        }

        private void productCategoryTree_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Clicks == 1 && e.Button == System.Windows.Forms.MouseButtons.Right)
                popupMenu1.ShowPopup(productCategoryTree.PointToScreen(e.Location));
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            CategoryNameSN.EditValue = string.Empty;
            CategoryNameCN.EditValue = string.Empty;
        }


        private void btnSearch_Click(object sender, EventArgs e)
        {
            ICriterion criterion = GetCriterion();

            if(criterion==null)
            {
                Functions.ShowMessageBox("至少要指定一个搜索条件。");
                return;
            }
            currentObject = null;
            productCategoryTree.ClearNodes();
            IList<ProductCategoryBase> productCategories = productMgr.GetProductCategoryList(criterion);
            if (productCategories == null) return;
            foreach (ProductCategoryBase category in productCategories)
            {
                TreeListNode treeListNode = productCategoryTree.AppendNode(new object[] { category.CategoryChinese, category.CategorySpanish, category }, null);
                treeListNode.HasChildren = true;
                treeListNode.Tag = false;
            }
        }

        private void productCategoryTree_Click(object sender, EventArgs e)
        {
            if (productCategoryTree.Selection.Count > 0)
                currentObject = (ProductCategoryBase) productCategoryTree.Selection[0].GetValue("pME");
            barProperty.Enabled = barDelete.Enabled = currentObject != null;
        }

        #endregion

        #region 菜单事件

        private void barNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AddNewProductCategory();
        }

        private void barDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DeleteProductCategory();
        }

        private void barRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LoadCategoryTree();
        }

        private void barProperty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            UpdateProductCategory();
        }

        #endregion
    }
}
